﻿using System.ComponentModel;
using System.Reflection;

namespace Demo.Core.CommonExtension;

/// <summary>
/// 枚举扩展类
/// </summary>
public static class EnumExtensions
{
    /// <summary>
    /// 获取描述特性
    /// </summary>
    /// <param name="enumValue">枚举值</param>
    /// <returns></returns>
    public static string GetDescription(this Enum enumValue)
    {
        string value = enumValue.ToString();
        FieldInfo field = enumValue.GetType().GetField(value);
        object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);  //获取描述属性
        if (objs == null || objs.Length == 0)  //当描述属性没有时，直接返回名称
            return value;
        DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
        return descriptionAttribute.Description;
    }
}